<?php

/**
 * ObjectModel for fiche database table. 
 * @author Nicolas Legrand <n.legrand28@gmail.com>
 */
class FicheTheme extends ObjectModel
{
	
	public $id_theme;
	public $name;
	
	public static $definition = array(
	
  		'table' 	=> 'fichetheme',
  		'primary' 	=> 'id_theme',
  		'multilang' => false,
 		'fields' => array(
   			'id_theme' => array(
   				'type' => ObjectModel :: TYPE_INT
			),
			'name' => array(
   				'type' => ObjectModel :: TYPE_STRING, 
   				'required' => true
			)
  		)
	);
	
	public static function addTheme( $name )
	{
		$sql = "INSERT INTO `"._DB_PREFIX_  ."fichetheme` VALUES(null, '".$name."')";
		Db :: getInstance()->Execute($sql);
		Fiche::rewriteDynamicTranslations();
	}
	
	public static function killThemeById($id)
	{
		$sql = 'DELETE FROM ' . _DB_PREFIX_ . 'fichetheme WHERE id_theme = '.(int)($id);
		Db :: getInstance()->Execute($sql);
		Fiche::rewriteDynamicTranslations();
	}
	
	public static function findAll() 
	{
		$sql = 'SELECT * FROM ' . _DB_PREFIX_ . 'fichetheme';
		if ($rows = Db :: getInstance()->ExecuteS($sql)) {
			return ObjectModel :: hydrateCollection(__CLASS__, $rows);
		}
		return array();
	}
	
	public static function buildWhereClause($conditions)
	{
		$whereClause = '';
		$i = 0;
		
		foreach( $conditions as $key => $value )
		{
			$whereClause .= ($i == 0) ? ' WHERE ' : ' AND ';
			
			if ( is_array($value) )
			{
				if ( $value['operator'] == 'LIKE' )
				{
					$whereClause .= $value['column']." LIKE '%".$value['value']."%'";
				}
				else
				{
					$whereClause .= $value['column']." ".$value['operator']." '".$value['value']."'";
				}
			}
			else
			{
				$whereClause .= $key." = '".$value."'";
			}
			$i++;
		}
		
		return $whereClause;
	}
	
	public static function findThemeBy( $conditions, $orderBy = null, $asc = true)
	{
		$sql = 'SELECT * FROM ' . _DB_PREFIX_ . 'fichetheme '.Theme::buildWhereClause($conditions);
		
		if ( $start != -1 || $end != -1)
		{
			$sql .= ' LIMIT '.$start.', '.$end;
		}
		
		if ( $orderBy != null )
		{
			$sens = ( $asc == true ) ? 'ASC':'DESC';
			$sql .= ' ORDER BY '.$orderBy.' '.$sens;
		}
		
		if ($rows = Db :: getInstance()->ExecuteS($sql)) {
			return ObjectModel :: hydrateCollection(__CLASS__, $rows);
		}
		return array();
	}
	
	
	public function getName()
	{
		$trad = Translate::getModuleTranslation('fichevitrine', $this->name, 'translations');
		//$trad = Translate::getModuleTranslation('fichevitrine', $this->name );
		return $trad;
	}
}